<!--
 * @Author: your name
 * @Date: 2022-10-28 09:10:11
 * @LastEditTime: 2023-03-10 17:48:30
 * @LastEditors: yuhan
 * @Description: 项目管理
 * @FilePath: \apiadmin\src\views\projectAdmin\index.vue
-->
<template>
  <div class="project-admin">
    <el-card class="box-card bottom-in">
      <template #header>
        <div class="card-header">
          <el-button class="button" type="primary" @click="handleEdit('creat')" :icon="Plus"
            >新建项目</el-button
          >
        </div>
      </template>
      <el-table :data="dataTable.data" border style="width: 100%" v-loading="dataTable.loading">
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="projectName" label="项目名称" align="center" />
        <el-table-column prop="domian" label="域名" align="center" />
        <el-table-column prop="tokenKey" label="token" align="center" />
        <el-table-column prop="updatedTime" label="修改时间" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.updatedTime, "YYYY-MM-DD hh:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260px" align="center" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              :icon="FolderOpened"
              size="small"
              @click="handleEdit('interProject', scope.row)"
              >进入项目</el-button
            >
            <el-button type="primary" plain size="small" @click="handleEdit('update', scope.row)"
              >修改</el-button
            >
            <el-popconfirm title="确定删除?" @confirm="handleEdit('delete', scope.row)">
              <template #reference>
                <el-button plain size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="sizes, prev, pager, next, total"
        background
        :current-page="dataTable.pageNo"
        v-model:page-size="dataTable.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :total="dataTable.total"
        @size-change="
          (pageSize) => {
            dataTable.pageNo = 1; // 重置到第一页
            dataTable.pageSize = pageSize;
            getTableData();
          }
        "
        @current-change="
          (pageNo) => {
            dataTable.pageNo = pageNo;
            getTableData();
          }
        "
      />
    </el-card>
    <el-dialog
      class="editDialog"
      v-model="editDialog.visible"
      :title="getEditDialogTitle"
      width="820px"
      center
      :close-on-click-modal="false"
      :before-close="closeEditDialog"
    >
      <el-form
        ref="dataForm"
        class="dataForm"
        :model="editDialog.formData"
        status-icon
        :rules="editDialog.rules"
        label-width="100px"
      >
        <el-form-item :label="`${page_config.formItem.projectName.name}`" prop="projectName">
          <el-input
            v-model="editDialog.formData.projectName"
            :placeholder="page_config.formItem.projectName.placeholder"
            clearable
          />
        </el-form-item>
        <el-form-item :label="`${page_config.formItem.domian.name}`" prop="domian">
          <el-input
            v-model="editDialog.formData.domian"
            :placeholder="page_config.formItem.domian.placeholder"
            clearable
          />
        </el-form-item>
        <el-form-item :label="`${page_config.formItem.header.name}`">
          <el-row
            v-for="(headerItem, headerItemIndex) in editDialog.formData.header"
            :key="headerItemIndex"
          >
            <el-col :span="9">
              <el-form-item
                :prop="`header[${headerItemIndex}].key`"
                :rules="editDialog.rules.headerKey"
              >
                <el-input v-model="headerItem.key" placeholder="例:Content-Type" clearable>
                  <template #prepend>Key</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :prop="`header[${headerItemIndex}].value`"
                :rules="editDialog.rules.headerValue"
              >
                <el-input
                  v-model="headerItem.value"
                  placeholder="例:application/json;charset=UTF-8"
                  clearable
                >
                  <template #prepend>Value</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button
                size="small"
                :icon="Minus"
                circle
                @click="editHeaderItem('delete', headerItemIndex)"
              />
            </el-col>
          </el-row>
          <p style="width: 100%; text-align: center">
            <el-button
              size="small"
              type="info"
              :icon="Plus"
              circle
              @click="editHeaderItem('add')"
            />
          </p>
        </el-form-item>
        <el-form-item :label="`${page_config.formItem.tokenKey.name}`" prop="tokenKey">
          <el-input
            v-model="editDialog.formData.tokenKey"
            :placeholder="page_config.formItem.tokenKey.placeholder"
            clearable
          />
        </el-form-item>
        <el-form-item :label="`${page_config.formItem.codeKey.name}`" prop="codeKey">
          <el-input
            v-model="editDialog.formData.codeKey"
            :placeholder="page_config.formItem.codeKey.placeholder"
            clearable
          />
        </el-form-item>
        <el-form-item :label="`${page_config.formItem.code.name}`" prop="code">
          <el-input
            v-model="editDialog.formData.code"
            :placeholder="page_config.formItem.code.placeholder"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <div>
            <!-- 空盒子占位 -->
          </div>
          <div>
            <el-button type="primary" @click="handleSubmit" :loading="editDialog.loading">
              {{ getEditDialogBtnLabel }}
            </el-button>
            <el-button @click="closeEditDialog"> 取消 </el-button>
          </div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { Plus, FolderOpened, Minus } from "@element-plus/icons-vue";
import { computed, onMounted, ref } from "vue";
import { formatTime, getFormDataUrl, ArrToObj, ObjToArr } from "@/utils/index.js";
import router from "@/router";
import apiUrl from "@/config/api.mjs";
import pageconfig from "@/config/pageConfig.js";
import { ElMessage, ElLoading } from "element-plus";
import store from "@/store";
// 页面配置
const page_config = pageconfig.projectAdmin;
// 页面api
const apis = apiUrl.projectAdmin;
const dataTable = ref({
  data: [],
  loading: false,
  pageNo: 1,
  pageSize: 10,
  total: 0,
});
const dataForm = ref(null);
const editDialog = ref({
  loading: false,
  visible: false,
  editType: "", // create 新增 update 修改
  rules: {
    projectName: [
      {
        required: true,
        trigger: "blur",
        message: `请输入${page_config.formItem.projectName.name}`,
      },
    ],
    // domian: [
    //   {
    //     required: true,
    //     trigger: 'blur',
    //     message: `请输入${page_config.formItem.domian.name}`,
    //   },
    // ],
    headerKey: [
      {
        required: true,
        trigger: "blur",
        validator: (rule, value, cb) => {
          if (value) {
            cb();
          } else {
            cb(new Error("请输入key"));
          }
        },
      },
    ],
    headerValue: [
      {
        required: true,
        trigger: "blur",
        validator: (rule, value, cb) => {
          if (value) {
            cb();
          } else {
            cb(new Error("请输入value"));
          }
        },
      },
    ],
    codeKey: [
      {
        required: true,
        trigger: "blur",
        message: `请输入${page_config.formItem.codeKey.name}`,
      },
    ],
    code: [
      {
        required: true,
        trigger: "blur",
        message: `请输入${page_config.formItem.code.name}`,
      },
    ],
  },
  formData: {
    projectName: "",
    domian: "",
    header: [{ key: "", value: "" }],
    tokenKey: "",
    codeKey: "code",
    code: 200,
  },
});
// 项目弹框标题
const getEditDialogTitle = computed(() => {
  let returnTitle = "";
  switch (editDialog.value.editType) {
    case "create":
      returnTitle = "新建项目";
      break;
    case "update":
      returnTitle = "修改项目";
      break;
  }
  return returnTitle;
});
// 项目弹框底部按钮文案
const getEditDialogBtnLabel = computed(() => {
  let btnLabel = "";
  switch (editDialog.value.editType) {
    case "create":
      btnLabel = "保存";
      break;
    case "update":
      btnLabel = "更新";
      break;
  }
  return btnLabel;
});
// 获取表格数据
const getTableData = () => {
  dataTable.value.loading = true;
  dataTable.value.data = [];
  getFormDataUrl("get", apis.dataList, {
    pageNo: dataTable.value.pageNo,
    pageSize: dataTable.value.pageSize,
  })
    .then((res) => {
      if (res) {
        dataTable.value.data = res?.records.map((item) => {
          return {
            ...item,
            header: ObjToArr(JSON.parse(item.header)),
          };
        });
        dataTable.value.total = res?.total;
      }
    })
    .finally(() => {
      dataTable.value.loading = false;
    });
};
// 初始化项目弹窗
const initEditDialog = (initformData = "") => {
  const formData = JSON.parse(JSON.stringify(initformData));
  editDialog.value.formData = {
    projectName: formData?.projectName || "",
    domian: formData?.domian || "",
    header: formData ? formData.header : [],
    tokenKey: formData?.tokenKey || "",
    codeKey: formData?.codeKey || "code",
    code: formData ? formData.code : 200,
  };
  // 更新情况下保存id，接口更新需要
  if (formData) {
    editDialog.value.formData.id = formData.id;
  }
};
// 打开项目编辑弹框
const openEditDialog = (formData) => {
  initEditDialog(formData);
  editDialog.value.visible = true;
};
// 关闭项目编辑弹框
const closeEditDialog = () => {
  dataForm.value.clearValidate();
  editDialog.value.visible = false;
  editDialog.value.title = "";
  initEditDialog();
};
// 操作统一入口
const handleEdit = (editType, row) => {
  switch (editType) {
    case "creat":
      editDialog.value.editType = "create";
      openEditDialog();
      break;
    case "interProject":
      store.dispatch("project/setProject", { ...row });
      router.push({
        name: "Overview",
      });
      break;
    case "update":
      editDialog.value.editType = "update";
      openEditDialog(row);
      break;
    case "delete":
      handleDelete(row.id);
      break;
    default:
      break;
  }
};
// 编辑项目增加请求头
const editHeaderItem = (type, index) => {
  switch (type) {
    case "add":
      editDialog.value.formData.header.push({
        key: "",
        value: "",
      });
      break;
    case "delete":
      editDialog.value.formData.header.splice(index, 1);
      break;
  }
};
// 删除项目
const handleDelete = (id) => {
  getFormDataUrl("get", `${apis.delete}/${id}`)
    .then((res) => {
      ElMessage.success("操作成功");
      getTableData();
    })
    .finally(() => {});
};
// 确定操作 新建/修改项目
const handleSubmit = () => {
  dataForm.value.validate((valid) => {
    if (valid) {
      let api = "";
      let param = {
        ...editDialog.value.formData,
        header: JSON.stringify(ArrToObj(editDialog.value.formData.header)),
      };
      switch (editDialog.value.editType) {
        case "create":
          api = apis.create;
          break;
        case "update":
          api = apis.update;
          break;
      }
      editDialog.value.loading = true;
      const loading = ElLoading.service({
        lock: true,
        text: "Loading",
      });
      getFormDataUrl("post", api, param)
        .then((res) => {
          ElMessage.success("操作成功");
          closeEditDialog();
          getTableData();
        })
        .finally(() => {
          editDialog.value.loading = false;
          loading.close();
        });
    }
  });
};

onMounted(() => {
  getTableData();
});
</script>
<style lang="scss" scoped>
.project-admin {
  .box-card {
    width: 100%;
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .input {
        width: 300px;
      }
    }
  }
  .editDialog {
    .dataForm {
      .el-row {
        width: 100%;
        justify-content: space-between;
        margin: 0 0 15px 0;
      }
    }
    .dialog-footer {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
